package com.wing.product.controller.admin;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.annotation.RequestObjectFieldIgnore;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.dict.model.entity.DictLabel;
import com.wing.dict.service.DictLabelService;
import com.wing.product.model.entity.*;
import com.wing.product.service.*;
import com.wing.product.strategy.AbstractTOrderService;
import com.wing.sell.model.response.OrderSkuDetailSearchVo;
import com.wing.system.service.EnterpricceIdService;
import com.wing.web.excel.DownExcelUtil;
import com.wing.web.excel.ExcelUtil;
import com.wing.web.excel.ProductExcelIn;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author
 */
@Validated
@Api(value = "Admin-产品管理", tags = "#/product/product")
@RestController("productController")
@RequestMapping("product/admin/product")
@Slf4j
public class ProductController {

    @Autowired
    private ProductService productService;
    @Autowired
    private ProductCategoryService productCategoryService;
    @Autowired
    private ProductCategoryExtService productCategoryExtService;
    @Autowired
    private ProductTypeService productTypeService;
    @Autowired
    private ProductUnitService productUnitService;
    @Autowired
    private ProductDetailAttributeService productDetailAttributeService;
    @Autowired
    private ProductDetailSpecService productDetailAttributeValueService;
    @Autowired
    private EnterpricceIdService enterpricceIdService;
    @Autowired
    private ProductDetailService productDetailService;
    @Autowired
    private ProductBrandService productBrandService;
    @Autowired
    private DynamicService dynamicService;

    @Autowired
    private AbstractTOrderService abstractOrderService;

    @Autowired
    private DictLabelService dictLabelService;

    @Autowired
    private ProcessLineTemplateService processLineTemplateService;

    @ApiOperation(value = "查询所有产品", notes = "搜索")
    @GetMapping("/list")
    public PageResult<Product> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit,
            @RequestParam(defaultValue = "create_time") String sort,
            @RequestParam(defaultValue = "asc") String order,
            String productCode,
            String name,
            String dataSource,
            String materialNature,
            Long productTypeId) {
        Page<Product> pg = new Page<>(page, limit);
        Map map = new HashMap();
        map.put("productCode", productCode);
        map.put("name", name);
        map.put("materialNature", materialNature);
        map.put("dataSource", dataSource);
        map.put("productTypeId", productTypeId);

        IPage<Product> list = productService.pageList4app(pg, map);
        //关联相关业务属性
        list.getRecords().parallelStream().forEach(product -> {
            //产品SKU
            QueryWrapper<ProductDetail> detailQueryWrapper = new QueryWrapper<>();
            detailQueryWrapper.eq("product_id", product.getId());
            List<ProductDetail> detailList = productDetailService.list(detailQueryWrapper);
            product.setProductDetailList(detailList);
        });
        return new PageResult<>(list.getRecords(), list.getTotal());
    }


    @ApiOperation(value = "添加产品", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@RequestBody Product product) {
        try {
            productService.add(product);
            return JsonResult.success("添加成功");
        } catch (Exception e) {
            log.error("添加失败:", e);
            return JsonResult.fail(e.getMessage());
        }
    }


    @ApiOperation(value = "修改产品", notes = "修改")
    @PostMapping("/update")
    public JsonResult update(@RequestBody Product product) {
        try {
            productService.updateProductById(product);
            return JsonResult.success("修改成功！");
        } catch (Exception e) {
            return JsonResult.fail("修改失败:" + e.getMessage());
        }
    }


    @ApiOperation(value = "删除产品", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productId", value = "产品id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Long productId) {
        try {
            productService.deleteProductById(productId);
            return JsonResult.success("删除成功");
        } catch (Exception be) {
            return JsonResult.fail("删除失败");
        }
    }


    @GetMapping("/getAllProductByType")
    public JsonResult getAllProductByType(Integer type) {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", type);
        List<Product> product = productService.list(queryWrapper);
        return JsonResult.success(product);
    }


    @GetMapping("/getProductById")
    public JsonResult<Product> getProductById(Long productId) {
        Product product = productService.get4appById(productId);
        return JsonResult.success(product);
    }

    @ApiOperation(value = "根据productCode查询产品", notes = "查询")
    @GetMapping("/getProductByCode")
    public JsonResult<List<Product>> getProductByCode(@RequestParam(name = "productCode") String productCode) {
        List<Product> productList = productService.list(new LambdaQueryWrapper<Product>().eq(Product::getProductCode, productCode));
        return JsonResult.success(productList);
    }


    /**
     * 下载产品数据录入excel模板
     */
    @ApiOperation(value = "下载产品数据录入excel模板")
    @GetMapping("/template")
    public void template(HttpServletResponse response, HttpServletRequest request) throws IOException {
        // 字典数据
        List<DictLabel> dictLabelList = dictLabelService.list(null);

        String[] headerArr = {"货品名称(*)", "货品编码(*)", "历史品名", "历史货号", "规格码", "物料类别性质(*)", "所属类别(*)", "物料分类(*)", "库存计量方式", "基础单位(*)", "是否自产产品", "是否委外生产", "工艺线路", "是否可以销售", "安全库存阈值", "呆滞时长阈值(天)", "质保期(天)", "折旧时长(月)", "数据来源", "是否一物一码", "是否批次管理", "是否先进先出", "备注"};
        List<String[]> downData = new ArrayList<>();
        List<String> indexArr = new ArrayList<>();
        StringBuffer tempStr = new StringBuffer();

        //物料类别性质
        List<DictLabel> natureList = dictLabelList.stream().filter(t -> "sys_product_type_nature".equals(t.getDictType())).collect(Collectors.toList());
        String[] natureData = new String[]{natureList.stream().map(t -> t.getLabelName()).collect(Collectors.joining(","))};
        indexArr.add("5");
        downData.add(natureData);
        //所属类别
        QueryWrapper<ProductType> productTypeQueryWrapper = new QueryWrapper<>();
//        productTypeQueryWrapper.eq("final_classify_status", 0);
        productTypeQueryWrapper.orderByAsc("sort_number");
        List<ProductType> productTypeList = productTypeService.list(productTypeQueryWrapper);
        String[] productTypeData = new String[]{productTypeList.stream().map(t -> t.getName()).collect(Collectors.joining(","))};
        indexArr.add("6");
        downData.add(productTypeData);
        //物料分类
        QueryWrapper<ProductCategory> productCategoryQueryWrapper = new QueryWrapper<>();
        productCategoryQueryWrapper.eq("is_final", 1);
        List<ProductCategory> productCategoryListList = productCategoryService.list(productCategoryQueryWrapper);
        String[] productCategoryData = new String[productCategoryListList.size()];
        for (int i = 0; i < productCategoryListList.size(); i++) {
            productCategoryData[i] = productCategoryListList.get(i).getName();
        }
        indexArr.add("7");
        downData.add(productCategoryData);
        //库存计量方式
        List<DictLabel> calculateWayList = dictLabelList.stream().filter(t -> "sys_product_detail_calculate_way".equals(t.getDictType())).collect(Collectors.toList());
        String[] calculateWayData = new String[calculateWayList.size()];
        for (int i = 0; i < calculateWayList.size(); i++) {
            calculateWayData[i] = calculateWayList.get(i).getLabelName();
        }
        indexArr.add("8");
        downData.add(calculateWayData);
        //基础单位
        List<DictLabel> baseUnitList = dictLabelList.stream().filter(t -> "sys_product_detail_base_unit".equals(t.getDictType())).collect(Collectors.toList());
        String[] baseUnitData = new String[baseUnitList.size()];
        for (int i = 0; i < baseUnitList.size(); i++) {
            baseUnitData[i] = baseUnitList.get(i).getLabelName();
        }
        indexArr.add("9");
        downData.add(baseUnitData);
        //是否自产产品
        String[] yesNodata = new String[]{"是", "否"};
        indexArr.add("10");
        downData.add(yesNodata);
        //是否委外生产
        indexArr.add("11");
        downData.add(yesNodata);
        //工艺线路
        QueryWrapper<ProcessLineTemplate> processLineTemplateQueryWrapper = new QueryWrapper<>();
        List<ProcessLineTemplate> processLineTemplateList = processLineTemplateService.list(processLineTemplateQueryWrapper);
        String[] processLineTemplateData = new String[processLineTemplateList.size()];
        for (int i = 0; i < processLineTemplateList.size(); i++) {
            processLineTemplateData[i] = processLineTemplateList.get(i).getName();
        }
        indexArr.add("12");
        downData.add(processLineTemplateData);
        //是否可以销售
        indexArr.add("13");
        downData.add(yesNodata);
        //数据来源
        List<DictLabel> dataSourceList = dictLabelList.stream().filter(t -> "sys_product_detail_data_source".equals(t.getDictType())).collect(Collectors.toList());
        String[] dataSourceData = new String[dataSourceList.size()];
        for (int i = 0; i < dataSourceList.size(); i++) {
            dataSourceData[i] = dataSourceList.get(i).getLabelName();
        }
        indexArr.add("18");
        downData.add(dataSourceData);
        //是否一物一码
        indexArr.add("19");
        downData.add(yesNodata);
        //是否批次管理
        indexArr.add("20");
        downData.add(yesNodata);
        //是否先进先出
        indexArr.add("21");
        downData.add(yesNodata);
        DownExcelUtil.createExcelTemplate(response, request, "产品导入模板", Arrays.asList(headerArr), downData, indexArr);
    }


    /**
     * 导入excel
     */
    @ApiOperation(value = "导入excel")
    @PostMapping("/importExcel")
    public JsonResult importExcel(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return JsonResult.fail("上传文件为空！");
        }
        try {
            //获取原始的文件名
            String originalFilename = file.getOriginalFilename();
            String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
            ExcelUtil<ProductExcelIn> reader = new ExcelUtil<>();
            InputStream is = file.getInputStream();
            List<ProductExcelIn> list = reader.read(is, ProductExcelIn.class);
            //List<Product> productList = new ArrayList<>();
            Map<String, Product> productMap = new HashMap<String, Product>();
            if (CollectionUtils.isEmpty(list)) {
                return JsonResult.fail("请在表格中添加数据！");
            }
            productService.importExcel(list);
        } catch (BusinessException e) {
            log.error("导入文件异常！异常信息:", e);
            return JsonResult.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error("上传文件异常！异常信息:", e);
            return JsonResult.exception("上传文件异常！异常信息:" + e.getMessage());
        }
        return JsonResult.success("导入成功！");
    }

    @ApiOperation(value = "查询订单物料", notes = "查询-orderSku")
    @GetMapping("/getQuantityBy")
    public JsonResult getQuantityBy(@RequestParam("type")String type, @RequestParam("orderId") Long orderId) {
        List<OrderSkuDetailSearchVo> detailBy = this.abstractOrderService.getDetailBy(type, orderId);
        return JsonResult.success(detailBy);
    }
}
